#include "camerajson.h"

CameraJson::CameraJson(QObject *parent) :
    QObject(parent)
{
    ServerConnected = false;
    socket_cot=0;
    this->tcp_socket = new QTcpSocket(this);
    connect(this->tcp_socket,SIGNAL(readyRead()),this,SLOT(socket_rec()));
    connect(tcp_socket, SIGNAL(connected()), this, SLOT(socket_connected()));
    connect(tcp_socket, SIGNAL(disconnected()), this, SLOT(socket_desconnected()));
    connect(tcp_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayshortError(QAbstractSocket::SocketError)));

    link_Timer = new QTimer();
    connect(link_Timer,SIGNAL(timeout()),SLOT(linkTimerOver())); ///先关闭长链接
    connect(link_Timer,SIGNAL(timeout()),SLOT(socket_send()));
    this->link_Timer->start(LINK_TIME);
}

void CameraJson::linkTimerOver()
{
    this->socket_link(this->camerarIp);
}

void CameraJson::socket_link(QString ip)
{
    //short link
    this->camerarIp = ip;
    qDebug()<<"CameraJson::socket_link"<<ServerConnected;
    if(ServerConnected)
    {
        return;
    }
    if(tcp_socket->state()== QAbstractSocket::ConnectedState)
    {
        tcp_socket->abort();
        tcp_socket->close();
        tcp_socket->disconnectFromHost();
        this->picBuffer.clear();
    }
    tcp_socket->connectToHost(this->camerarIp,8131);
}
void CameraJson::socket_rec()
{
    QByteArray data;
    QByteArray tcp_count;
    QString license;
    if(tcp_socket->bytesAvailable())
    {
        data=tcp_socket->readAll();
        QTextCodec *codec = QTextCodec::codecForName("GB2312");
        QString str = codec->toUnicode(data);
        qDebug()<<"***strProWebCar***"<<str;
        if(str.length()<10)
        {
            return;
        }
        QScriptEngine engine;
        QScriptValue sc = engine.evaluate("value="+str);

        //QString PlateResult=sc.property("PlateResult").toString ();
        QString Image=sc.property("imageformat").toString ();
        QString time=sc.property("timeSting").toString ();
        //qDebug()<<"PlateResult:"<<PlateResult;
        QScriptValue platsc = sc.property("PlateResult");
        license=platsc.property("license").toString();//车号
        qDebug()<<"CameraJson::socket_rec"<<Image<<time<<license;
    }
    // QPixmap photo;
    // name=query.value(0).toString();
    // photo.loadFromData(query.value(1).toByteArray(),"JPG");
    // emit carNumberRec(license,&photo);
}

void CameraJson::socket_connected() ///连接上回调函数
{
    ServerConnected = true;
    this->picBuffer.clear();
    this->packHeader.clear();
    usleep(180000);
    qDebug() << "send request:";
}
void CameraJson::socket_desconnected()
{
    ServerConnected = false;
    QPixmap aa;
    aa.loadFromData(this->picBuffer,0,Qt::AutoColor);
    emit carNumberRec("",&aa);
    this->packHeader.clear();
    this->picBuffer.clear();
}

void CameraJson::displayshortError(QAbstractSocket::SocketError)
{
    ServerConnected = false;
    //qDebug()<<this->camerarIp<<"error123:"<<this->tcp_socket_short->errorString();
}

QString CameraJson::GetIvsresult()
{
    cJSON *root;
    char *out;
    root=cJSON_CreateObject();
    cJSON_AddStringToObject(root, "cmd","ivsresult");
    cJSON_AddBoolToObject(root, "enable", true);
    cJSON_AddStringToObject(root, "format","json");
    cJSON_AddBoolToObject(root, "image",true);
    cJSON_AddNumberToObject(root, "image_type",0);
    out=cJSON_Print(root);
    QString send;
    send=QString(out).simplified();
    return send;
}

QString CameraJson::OpenDev(int falg)
{
    cJSON *root;
    QByteArray by;
    char *out;
    char*time;
    root=cJSON_CreateObject();
    cJSON_AddStringToObject(root, "cmd","ioctl");
    if(falg==0)
    {
    cJSON_AddStringToObject(root, "io","0");
    }else{
    cJSON_AddStringToObject(root, "io","1");
    }
    cJSON_AddStringToObject(root, "value","2");
    by=QString::number(DELAY_TIME).toLocal8Bit();
    time=by.data();
    cJSON_AddStringToObject(root, "delay",time);
    out=cJSON_Print(root);
    QString send;
    send=QString(out).simplified();
    qDebug()<<send;
    return send;
}

void CameraJson::socket_send()//当客户端需要请求车牌识别结果时，需要向IPC设备8200端口号发起连接，并发送u32Size为32，u32Type为 0x1007的数据包。
{
    qDebug()<<"camera::socket_long_send()="<<this->camerarIp<<ServerConnected;
    if(!ServerConnected)
    {
        return;
    }
    QByteArray send;
    this->packHeader.clear();
    this->picBuffer.clear();
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("GB2312"));
    QString str=GetIvsresult();
    GetHend(str);
    qDebug()<<"str"<<str;
    this->picBuffer=str.toLocal8Bit();
    send=this->packHeader.append(this->picBuffer);
    this->tcp_socket->write(send);
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
}

void CameraJson::GetHend(QString str)
{
    QString qs_data;
    unsigned char openDoorCmd[]={0x56,0x5A,0x00,0x00,0x00,0x00,0x00,0x00};
    QTextCodec *gb2312 = QTextCodec::codecForName("GB2312");
    QByteArray sendArray;
    sendArray = gb2312->fromUnicode(str);
    int m=sendArray.length();
    GetSocket_Count();
    openDoorCmd[3]=(char)socket_cot;
    //test.a=sendArray.length();
    //qToBigEndian(test.a,(uchar*)test.b);
    qToBigEndian(m,&openDoorCmd[4]);
    int mn=sizeof(openDoorCmd);
    QString str_data;
    for(int i=0;i<mn;i++)
    {
        str_data=QString::number(openDoorCmd[i],16);
        if(str_data.length()<2)
        {
            str_data=QString("%1").arg(openDoorCmd[i],2,16,QLatin1Char('0'));
        }
        qs_data+=str_data;
    }
    qDebug()<<"GetHend"<<qs_data;
    this->packHeader=qs_data.toLocal8Bit();
    //  strncpy(&openDoorCmd[4],(char)m,4);
    //   quint16 src = 8823;
    //   QByteArray byte_arry;
    //   uchar temp[2];
    //   qToBigEndian<quint16>(src, temp);
    //   byte_arry.append((char*)temp,2);

    //   union{
    //       int a;
    //       char b[4];
    //   }test1,test2;
    //   test1.a=0x61626364;
    //   test2.a=qFromBigEndian(test1.a);
    //   qDebug()<<test1.b[0]<<test1.b[1]<<test1.b[2]<<test1.b[3];
    //   qDebug()<<test2.b[0]<<test2.b[1]<<test2.b[2]<<test2.b[3];

    //   union{
    //       int a;
    //       char b[4];
    //   }test3,test4;
    //   test3.a=0x61626364;
    //   test4.a=qFromLittleEndian(test1.a);
    //   qToBigEndian(test3.a,(uchar*)test4.b);
    //   qDebug()<<test3.b[0]<<test3.b[1]<<test3.b[2]<<test3.b[3];
    //   qDebug()<<test4.b[0]<<test4.b[1]<<test4.b[2]<<test4.b[3];
}

void CameraJson::GetSocket_Count()
{
    if(socket_cot < 255)
    {
        socket_cot++;
    }else{
        socket_cot=0;
    }
}
